const express = require('express');
const router = express.Router();
const db = require('../config/database');
const { validatePagination } = require('../utils/validation');

// 获取模板列表
router.get('/', async (req, res) => {
  try {
    const { 
      page = 1, 
      pageSize = 20, 
      search,
      populate,
      'filters[templ_type][$eq]': typeId,
      'populate[img]': populateImg
    } = req.query;
    
    // 验证分页参数
    const { error } = validatePagination({ page: parseInt(page), pageSize: parseInt(pageSize) });
    if (error) {
      return res.status(400).json({ error: error.details[0].message });
    }
    
    // 确保参数为有效数字
    const pageNum = Math.max(1, parseInt(page) || 1);
    const pageSizeNum = Math.max(1, parseInt(pageSize) || 20);
    const offset = (pageNum - 1) * pageSizeNum;
    
    // 构建查询条件
    let whereClause = 'WHERE t.is_public = TRUE';
    const params = [];
    
    if (typeId) {
      whereClause += ' AND t.type_id = ?';
      params.push(Math.max(1, parseInt(typeId) || 1));
    }
    
    if (search) {
      whereClause += ' AND t.name LIKE ?';
      params.push(`%${search}%`);
    }
    
    // 查询总数
    const [countResult] = await db.query(
      `SELECT COUNT(*) as total FROM templates t ${whereClause}`,
      params
    );
    const total = countResult[0].total;
    
    // 查询数据
    const query = `
      SELECT 
        t.id,
        t.name,
        t.type_id,
        t.preview,
        t.thumbnail,
        t.width,
        t.height,
        t.json_data,
        t.tags,
        t.download_count,
        t.created_at,
        t.updated_at,
        ${populate === '*' ? 'tt.name as type_name' : 'NULL as type_name'}
      FROM templates t
      ${populate === '*' ? 'LEFT JOIN template_types tt ON t.type_id = tt.id' : ''}
      ${whereClause}
      ORDER BY t.created_at DESC
      LIMIT ? OFFSET ?
    `;
    
    const [rows] = await db.query(query, [...params, pageSizeNum, offset]);
    
    // 格式化数据
    const data = rows.map(row => ({
      id: row.id,
      attributes: {
        name: row.name,
        preview: row.preview,
        thumbnail: row.thumbnail,
        width: row.width,
        height: row.height,
        json: row.json_data ? JSON.parse(row.json_data) : null,
        tags: row.tags ? JSON.parse(row.tags) : [],
        download_count: row.download_count,
        createdAt: row.created_at,
        updatedAt: row.updated_at,
        ...(populate === '*' && row.type_name && {
          templ_type: {
            data: {
              id: row.type_id,
              attributes: {
                name: row.type_name
              }
            }
          }
        }),
        ...(populateImg === '*' && {
          img: {
            data: {
              id: row.id,
              attributes: {
                url: row.preview,
                thumbnail: row.thumbnail
              }
            }
          }
        })
      }
    }));
    
    res.json({
      data,
      meta: {
        pagination: {
          page: pageNum,
          pageSize: pageSizeNum,
          pageCount: Math.ceil(total / pageSizeNum),
          total
        }
      }
    });
  } catch (error) {
    console.error('获取模板列表失败:', error);
    res.status(500).json({ error: '获取模板列表失败' });
  }
});

// 获取单个模板详情
router.get('/:id', async (req, res) => {
  try {
    const { id } = req.params;
    const { populate, 'populate[img]': populateImg } = req.query;
    
    // 确保 id 为有效数字
    const templateId = Math.max(1, parseInt(id) || 1);
    
    const query = `
      SELECT 
        t.*,
        ${populate === '*' ? 'tt.name as type_name' : 'NULL as type_name'}
      FROM templates t
      ${populate === '*' ? 'LEFT JOIN template_types tt ON t.type_id = tt.id' : ''}
      WHERE t.id = ? AND t.is_public = TRUE
    `;
    
    const [rows] = await db.query(query, [templateId]);
    
    if (rows.length === 0) {
      return res.status(404).json({ error: '模板不存在' });
    }
    
    const row = rows[0];
    const data = {
      id: row.id,
      attributes: {
        name: row.name,
        preview: row.preview,
        thumbnail: row.thumbnail,
        width: row.width,
        height: row.height,
        json: row.json_data ? JSON.parse(row.json_data) : null,
        tags: row.tags ? JSON.parse(row.tags) : [],
        download_count: row.download_count,
        createdAt: row.created_at,
        updatedAt: row.updated_at,
        ...(populate === '*' && row.type_name && {
          templ_type: {
            data: {
              id: row.type_id,
              attributes: {
                name: row.type_name
              }
            }
          }
        }),
        ...(populateImg === '*' && {
          img: {
            data: {
              id: row.id,
              attributes: {
                url: row.preview,
                thumbnail: row.thumbnail
              }
            }
          }
        })
      }
    };
    
    // 增加下载次数
    await db.query(
      'UPDATE templates SET download_count = download_count + 1 WHERE id = ?',
      [templateId]
    );
    
    res.json({ data });
  } catch (error) {
    console.error('获取模板详情失败:', error);
    res.status(500).json({ error: '获取模板详情失败' });
  }
});

module.exports = router;